#ifndef __PARSEUTIL_H__
#define __PARSEUTIL_H__

#include "wfrest/HttpServer.h"
#include "workflow/MySQLResult.h"
#include "workflow/WFFacilities.h"
#include "User.h"
#include <string>
#include <map>
#include <sstream>
using namespace wfrest;
using namespace protocol;
using std::string;
using std::map;
using std::istringstream;

class ParseUtil{
public:
    static map<string,string> get_query_param(string &uri){
        map<string,string> result;
        string params = uri.substr(uri.find("?")+1);
        istringstream iss(params);
        string line;
        while (std::getline(iss,line,'&')) {
            auto pos = line.find('=');
            string key = line.substr(0, pos);
            string value = line.substr(pos+1);
            result[key] = value;
        }
        return result;
    }

    //验证token,验证成功
    static void verify_token(const HttpReq *req, HttpResp *resp, std::function<void(User)> cb) {
        string url;
        req->get_request_uri(url);
        map<string,string> params = get_query_param(url);
        string token = params["token"];

        string sql_query = "select * from tbl_user where username = '" + params["username"] + "';";
        resp->MySQL("mysql://root:200211@localhost/cloud_disk", sql_query,
            [resp, token, cb](MySQLResultCursor *cursor){
                User user{};
                if(cursor->get_cursor_status()==MYSQL_STATUS_GET_RESULT && cursor->get_rows_count()==1){
                    map<string,MySQLCell> record;
                    if(cursor->fetch_row(record)){
                        user.id = record["id"].as_int();
                        user.username = record["username"].as_string();
                        user.hashcode = record["password"].as_string();
                        user.salt = record["salt"].as_string();
                        user.createdAt = record["created_at"].as_datetime();
                    }
                }
                cb(user); // 把结果交给回调
            });
    }
};

#endif